<template>
  <div class="page">
    <BrandHeader>
      <template #title>光影漫荐</template>
    </BrandHeader>
    <div class="content">
      <div class="topbar">
        <button class="back-btn" @click="goBack" aria-label="返回上一页">返回</button>
        <h1 class="title">全部电影</h1>
      </div>

      <!-- 筛选栏 -->
      <div class="filters">
        <!-- 标题检索（模糊搜索，作用于“全部电影”） -->
        <div class="filter-group" style="min-width:280px">
          <label for="movie-search">搜索</label>
          <input
            id="movie-search"
            class="search-inline"
            type="text"
            v-model="searchText"
            placeholder="按标题搜索… 回车执行"
            @keyup.enter="doSearch"
            aria-label="按标题搜索电影"
          />
          <button class="search-btn" @click="doSearch">搜索</button>
          <button class="clear-btn" v-if="(searchText || searchQ)" @click="clearSearch">清除</button>
        </div>
        <div class="filter-group">
          <label>类型</label>
          <select v-model="selectedGenre" @change="onFilterChange">
            <option value="">全部</option>
            <option v-for="g in genreOptions" :key="g" :value="g">{{ g }}</option>
          </select>
        </div>
        <div class="filter-group">
          <label>年份</label>
          <select v-model="selectedYearRange" @change="onFilterChange">
            <option value="">全部</option>
            <option value="2020s">2020-2025</option>
            <option value="2010s">2010-2019</option>
            <option value="2000s">2000-2009</option>
            <option value="1990s">1990-1999</option>
            <option value="older">更早</option>
          </select>
        </div>
        <div class="filter-group">
          <label>语言</label>
          <select v-model="selectedLang" @change="onFilterChange">
            <option value="">全部</option>
            <option v-for="l in languageOptions" :key="l" :value="l">{{ l }}</option>
          </select>
        </div>
        <div class="filter-group">
          <label>排序</label>
          <select v-model="sortBy" @change="onFilterChange">
            <option value="hot">按热度</option>
            <option value="score">按高分</option>
            <option value="year">按年份新->旧</option>
          </select>
        </div>
        <div class="filter-group">
          <button class="reset-btn" @click="resetFilters">重置</button>
        </div>
        <div class="spacer" />
        <div class="result-info">共 {{ filteredCount }} 部影片</div>
      </div>

      <!-- 网格（7列 x 4行 = 每页28条） -->
      <div v-if="error" class="status error">{{ error }} <button class="retry-btn" @click="load">重试</button></div>
      <div v-else-if="loading" class="status loading">加载中…</div>
      <div v-else-if="!loading && filteredCount === 0" class="status empty">暂无影片 <button class="retry-btn" @click="load">重试</button></div>
      <div class="grid" v-else>
        <MovieCard
          v-for="m in pageItems"
          :key="m.id"
          :movie="m"
          :cardWidth="200"
          :posterHeight="260"
          @select="goDetail"
        />
      </div>

      <!-- 分页器 -->
      <div class="pager" v-if="totalPages > 1">
        <button class="page-btn" :disabled="page === 1" @click="toPrev">上一页</button>
        <span class="page-info">第 {{ page }} / {{ totalPages }} 页</span>
        <button class="page-btn" :disabled="page === totalPages" @click="toNext">下一页</button>
      </div>
    </div>
  </div>
  
</template>

<script setup>
import { onMounted, ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import BrandHeader from '@/components/BrandHeader.vue'
import MovieCard from '@/components/MovieCard.vue'
import { getMovieCatalog, getMovieCatalogOptions } from '@/services/api.js'

const router = useRouter()
const PER_PAGE = 28 // 7列 x 4行（服务端分页 page_size）
// 将评分很少的影片在“热度排序”时往后排的阈值
const MIN_RATING_COUNT = 10

const items = ref([])
const total = ref(0)
const loading = ref(false)
const error = ref('')
// 搜索关键词（来自路由 query.q）
const searchQ = ref('')
const searchText = ref('')

// 筛选状态
const selectedGenre = ref('')
const selectedYearRange = ref('')
const selectedLang = ref('')
const sortBy = ref('hot') // hot | score | year
const page = ref(1)
// 选项缓存
const genreOptions = ref([])

function parseYear(y) {
  const n = Number(String(y || '').slice(0, 4))
  return Number.isFinite(n) ? n : null
}

function mapMovie(m, idx) {
  // 保留可能的统计字段，便于排序
  const year = m.year ?? m.release_year ?? m.releaseDate ?? ''
  // 评分：若缺失则保持为 null（不要使用随机值干扰排序）
  const ratingRaw = m.predicted_rating ?? m.rating_mean ?? m.vote_average ?? null
  const rating = ratingRaw != null && ratingRaw !== '' ? Number(ratingRaw) : null
  // 评分人数与热度
  const ratingCountRaw = m.rating_count ?? m.ratingCount ?? m.vote_count ?? null
  const rating_count = ratingCountRaw != null && ratingCountRaw !== '' ? Number(ratingCountRaw) : null
  const popularityRaw = m.popularity ?? m.popularity_score ?? null
  const popularity = popularityRaw != null && popularityRaw !== '' ? Number(popularityRaw) : null
  return {
  id: m.movieId ?? m.id ?? idx,
    title: m.title ?? '未知标题',
    rating: rating,
  rating_count: rating_count,
  popularity: popularity,
    poster: m.poster || m.poster_path || '',
    overview: m.overview || '',
    year: year,
    yearNum: parseYear(year),
    genres: m.genres || '',
    original_language: m.original_language || m.language || ''
  }
}

// 过滤年份区间
function filterByYearRange(arr, yearRange) {
  if (!yearRange) return arr
  let min = 0, max = 9999
  if (yearRange === '2020s') { min = 2020; max = 2025 }
  else if (yearRange === '2010s') { min = 2010; max = 2019 }
  else if (yearRange === '2000s') { min = 2000; max = 2009 }
  else if (yearRange === '1990s') { min = 1990; max = 1999 }
  else if (yearRange === 'older') { max = 1989 }
  return arr.filter(x => {
    const y = Number(x.yearNum)
    return Number.isFinite(y) && y >= min && y <= max
  })
}

// 本地“热度”排序：评分人数多的排前面，评分人数相同则评分高的排前面，再按年份新旧
function sortByHotLocal(arr) {
  return arr.slice().sort((a, b) => {
    const cA = Number(a.rating_count ?? 0)
    const cB = Number(b.rating_count ?? 0)
    if (cA !== cB) return cB - cA
    const rA = Number(a.rating)
    const rB = Number(b.rating)
    if (Number.isFinite(rA) && Number.isFinite(rB) && rA !== rB) return rB - rA
    const yA = Number(a.yearNum)
    const yB = Number(b.yearNum)
    if (Number.isFinite(yA) && Number.isFinite(yB) && yA !== yB) return yB - yA
    return 0
  })
}

// 本地“高分”排序：只展示有评分的电影，评分高的排前面，评分人数多的排前面，再按年份新旧
function sortByScoreLocal(arr) {
  return arr.filter(x => Number.isFinite(Number(x.rating))).sort((a, b) => {
    const rA = Number(a.rating)
    const rB = Number(b.rating)
    if (rA !== rB) return rB - rA
    const cA = Number(a.rating_count ?? 0)
    const cB = Number(b.rating_count ?? 0)
    if (cA !== cB) return cB - cA
    const yA = Number(a.yearNum)
    const yB = Number(b.yearNum)
    if (Number.isFinite(yA) && Number.isFinite(yB) && yA !== yB) return yB - yA
    return 0
  })
}

async function loadOptions() {
  try {
    const res = await getMovieCatalogOptions()
    const genres = Array.isArray(res?.data?.genres) ? res.data.genres : []
    genreOptions.value = genres
  } catch (e) {
    // 选项加载失败不阻塞
  }
}

async function load() {
  loading.value = true
  error.value = ''
  try {
    const res = await getMovieCatalog({
      page: page.value,
      page_size: PER_PAGE,
      genre: selectedGenre.value || '',
      year_range: selectedYearRange.value || '',
      lang: selectedLang.value || '',
      sort: sortBy.value || 'hot',
      q: (searchQ.value || '').trim()
    })
    const data = res?.data || {}
    let list = Array.isArray(data.items) ? data.items.map(mapMovie) : []
    // 先按年份区间过滤
    list = filterByYearRange(list, selectedYearRange.value)
    // 排序逻辑
    if ((sortBy.value || 'hot') === 'hot') {
      list = sortByHotLocal(list)
    } else if ((sortBy.value || '') === 'score') {
      list = sortByScoreLocal(list)
    } else if ((sortBy.value || '') === 'year') {
      // 年份新->旧
      list = list.slice().sort((a, b) => {
        const yA = Number(a.yearNum)
        const yB = Number(b.yearNum)
        if (Number.isFinite(yA) && Number.isFinite(yB) && yA !== yB) return yB - yA
        return 0
      })
    }
    items.value = list
    // 后端已做了搜索过滤，total 表示当前筛选/搜索后的条目数
    total.value = Number.isFinite(Number(data.total)) ? Number(data.total) : list.length
  } catch (e) {
    // 打印更详细的错误信息
    const status = e?.response?.status
    const msg = e?.message || e?.toString?.() || '未知错误'
    console.error('[Movies] 获取电影列表失败', { status, msg, url: e?.config?.url })
    // 如果是大数量失败，尝试降级重试更小数量
    try {
      // 降级重试：请求第 1 页
      console.debug('[Movies] 降级重试 catalog page=1')
  const res2 = await getMovieCatalog({ page: 1, page_size: PER_PAGE, sort: sortBy.value || 'hot', q: (searchQ.value || '').trim() })
      const data2 = res2?.data || {}
      let list2 = Array.isArray(data2.items) ? data2.items.map(mapMovie) : []
      if ((sortBy.value || 'hot') === 'hot') {
        list2 = sortByHotLocal(list2)
      }
      items.value = list2
      total.value = Number.isFinite(Number(data2.total)) ? Number(data2.total) : list2.length
      if (list2.length > 0) {
        error.value = ''
        return
      }
      error.value = '获取电影列表失败'
    } catch (e2) {
      const status2 = e2?.response?.status
      const msg2 = e2?.message || e2?.toString?.() || '未知错误'
      console.error('[Movies] 降级重试失败', { status: status2, msg: msg2, url: e2?.config?.url })
      error.value = '获取电影列表失败'
    }
  } finally {
    loading.value = false
  }
}

// 语言选项：服务端未提供全量语言列表时，使用常见语言
const languageOptions = computed(() => ['en','zh','ja','ko','fr','de'])

// 组合筛选 + 排序
// 服务端分页数据
const filteredCount = computed(() => total.value)
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / PER_PAGE)))
const pageItems = computed(() => items.value)

function onFilterChange() {
  page.value = 1
  load()
}
function resetFilters() {
  selectedGenre.value = ''
  selectedYearRange.value = ''
  selectedLang.value = ''
  sortBy.value = 'hot'
  page.value = 1
  load()
}

function goDetail(id) {
  if (!id) return
  router.push({ name: 'movie', params: { id } })
}
function goBack() {
  if (window.history.length > 1) router.back()
  else router.push('/recommend')
}
function toPrev() { if (page.value > 1) { page.value--; load(); } }
function toNext() { if (page.value < totalPages.value) { page.value++; load(); } }

onMounted(() => {
  // 读取 URL 中的 ?q= 作为搜索
  const q = (router.currentRoute.value.query?.q || '').toString()
  searchQ.value = q
  searchText.value = q
  loadOptions()
  load()
})

// 监听路由变化（例如从首页带不同关键词跳转到 /movies?q=xxx）
watch(() => router.currentRoute.value.query?.q, (newQ) => {
  const q = (newQ || '').toString()
  if (q !== searchQ.value) {
    searchQ.value = q
    searchText.value = q
    page.value = 1
    load()
  }
})

function doSearch() {
  const q = (searchText.value || '').trim()
  // 更新路由 query 以触发监听和加载
  if (q) {
    router.push({ name: 'movies', query: { q } })
  } else {
    // 清除 q
    router.push({ name: 'movies' })
  }
}

function clearSearch() {
  searchText.value = ''
  router.push({ name: 'movies' })
}
</script>

<script>
export default {
  name: 'MoviesPage'
}
</script>

<style scoped>
.page { min-height: 100vh; background: #0f0f0f; color: #fff; }
.content { padding: 10px 16px 20px; }
.topbar { display:flex; align-items: center; gap: 12px; margin: 4px 0 10px; }
.back-btn {
  background: #fff;
  color: #000;
  border: 1px solid #e5e5e5;
  border-radius: 10px;
  padding: 8px 14px;
  font-size: 16px;
  font-weight: 700;
  cursor: pointer;
  transition: background .15s ease, transform .1s ease;
}
.back-btn:hover { background: #f2f2f2; transform: translateY(-1px); }
.back-btn:focus-visible { outline: 2px solid #000; outline-offset: 2px; }
.title { margin: 0; font-size: 22px; font-weight: 700; }

.filters {
  display: flex;
  flex-wrap: wrap;
  gap: 12px 16px;
  align-items: center;
  background: #141414;
  border: 1px solid #242424;
  border-radius: 12px;
  padding: 12px;
  margin-bottom: 16px;
}
.filters:has(input.search-inline) { align-items: center; }
.filter-group { display:flex; gap: 8px; align-items:center; }
.filter-group label { color:#ddd; font-size: 14px; }
input.search-inline {
  background: #1f1f1f;
  color: #fff;
  border: 1px solid #333;
  border-radius: 8px;
  padding: 6px 10px;
  min-width: 200px;
}
select {
  background: #1f1f1f;
  color: #fff;
  border: 1px solid #333;
  border-radius: 8px;
  padding: 6px 10px;
}
.search-btn { background:#fff; color:#000; border:1px solid #e5e5e5; border-radius:8px; padding:6px 12px; cursor:pointer; }
.clear-btn { background:#2a2a2a; color:#ddd; border:1px solid #333; border-radius:8px; padding:6px 12px; cursor:pointer; }
.clear-btn:hover { background:#333; }
.reset-btn {
  background: #2a2a2a;
  color: #ddd;
  border: 1px solid #333;
  border-radius: 8px;
  padding: 6px 12px;
  cursor: pointer;
}
.reset-btn:hover { background:#333; }
.spacer { flex: 1; }
.result-info { color: #aaa; font-size: 13px; }

.status { 
  background: #141414; border: 1px solid #242424; border-radius: 10px; padding: 12px 14px; color: #ccc; margin: 10px 0; 
}
.status.error { color: #ffb3b3; border-color: #5a1f1f; background: #1e1212; }
.status.loading { color: #ddd; }
.status.empty { color: #bbb; }
.retry-btn { margin-left: 10px; background:#fff; color:#000; border:1px solid #e5e5e5; border-radius: 6px; padding: 4px 10px; cursor: pointer; }

/* 7列网格，卡片 200px 宽，和热门页保持一致 */
.grid {
  display: grid;
  grid-template-columns: repeat(7, 200px);
  gap: 28px;
  justify-content: start;
}

.pager {
  display:flex; align-items:center; gap: 12px;
  justify-content: center;
  margin-top: 18px;
}
.page-btn {
  background:#fff; color:#000; border: 1px solid #e5e5e5; border-radius: 8px; padding: 6px 12px; cursor: pointer;
}
.page-btn:disabled { opacity: .5; cursor: not-allowed; }
.page-info { color:#ddd; font-size: 14px; }

@media (max-width: 1400px) {
  .grid { grid-template-columns: repeat(6, 200px); }
}
@media (max-width: 1200px) {
  .grid { grid-template-columns: repeat(5, 200px); }
}
@media (max-width: 1000px) {
  .grid { grid-template-columns: repeat(4, 200px); }
}
@media (max-width: 820px) {
  .grid { grid-template-columns: repeat(3, 200px); }
}
@media (max-width: 620px) {
  .grid { grid-template-columns: repeat(2, 200px); }
}
</style>
